package com.lori.netshop.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lori.netshop.dao.RedisDao;
import com.lori.netshop.mapper.TbItemCatMapper;
import com.lori.netshop.pojo.CatNode;
import com.lori.netshop.pojo.CatResult;
import com.lori.netshop.pojo.TbContent;
import com.lori.netshop.pojo.TbItemCat;
import com.lori.netshop.pojo.TbItemCatExample;
import com.lori.netshop.pojo.TbItemCatExample.Criteria;
import com.lori.netshop.service.ItemCatService;
import com.lori.netshop.util.StringUtil;
@Service
public class ItemCatServiceimp implements ItemCatService {
	@Autowired
	private TbItemCatMapper tbItemCatMapper;
	//注入redis
	@Autowired
	private RedisDao redisDaoimp;
	//获取资源文件的值
	@Value("${INDEX_ITEMCAT_REDIS_KEY}")
	private String INDEX_ITEMCAT_REDIS_KEY;
	@Override
	public CatResult getCatresult() {
		CatResult catResult = new CatResult();
		catResult.setData(getCatList(0));
		return catResult;
	}
	public List getCatList(long parentid){
		ObjectMapper object = null;
		//将缓存中的数据取出
		try {
			//从redis集群获取数据
			String data = redisDaoimp.hget(INDEX_ITEMCAT_REDIS_KEY, parentid+"");
			if(!StringUtil.isEmpty(data)){
				object = new ObjectMapper();
				JavaType javatype = object.getTypeFactory().constructParametricType(ArrayList.class, CatNode.class);
				List<CatNode> readValue = object.readValue(data, javatype);
				return readValue;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//获得分类数据
		TbItemCatExample example = new TbItemCatExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentid);
		List<TbItemCat> catlist = tbItemCatMapper.selectByExample(example);
		//目录结构
		List data = new ArrayList();
		//遍历
		for(TbItemCat tbItemCat:catlist){
			CatNode catnode = new CatNode();
			catnode.setUrl("/products/"+tbItemCat.getId()+".html");
			//判断是否是第一层
			if(parentid == 0){
				catnode.setName("<a href='/products/"+tbItemCat.getId()+".html'>"+tbItemCat.getName()+"</a>");
			}else{
				catnode.setName(tbItemCat.getName());
			}
			//如果是父节点则递归
			if(tbItemCat.getIsParent()){
				List catList2 = getCatList(tbItemCat.getId());
				catnode.setItem(catList2);
				data.add(catnode);
			}else{
				data.add("/products/"+tbItemCat.getId()+".html | "+tbItemCat.getName());
			}
		}
		
		//将查询得来的数据存入redis缓存中
		try {
			//将数据转成字符串
			object = new ObjectMapper();
			String json = object.writeValueAsString(data);
			//将数据存入redis缓存中
			redisDaoimp.hset(INDEX_ITEMCAT_REDIS_KEY, parentid+"", json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

}
